package com.woniu.filters;

import com.woniu.utils.MyJsonWebToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Rain
 * @Description :
 * @date 2022/09/06 11:10
 */
@Component
public class JWTFilter extends BasicHttpAuthenticationFilter {
    private final String TOKENKEY = "Authorization";

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;

        response1.setHeader("Access-Control-Allow-Origin", request1.getHeader("Origin"));
        response1.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        response1.setHeader("Access-Control-Allow-Headers", request1.getHeader("Access-Control-Request-Headers"));

        if (request1.getMethod().equals(RequestMethod.OPTIONS.name())) {
            response1.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request1, response1);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //不为空则进入登录方法
        if (isLoginAttempt(request, response)) {
            try {
                executeLogin(request, response);
            } catch (Exception e) {
                e.printStackTrace();
                response401(request, response);
                return false;
            }
            return false;
        }
        response401(request, response);
        return true;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest request1 = (HttpServletRequest) request;
        //判断token是否为空
        String token = request1.getHeader(TOKENKEY);

        return token != null;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest request1 = (HttpServletRequest) request;
        //通过request拿到token
        String token = request1.getHeader(TOKENKEY);

        //login()方法进入自定义realm,传入自定义封装token类
        getSubject(request, response).login(new MyJsonWebToken(token));
        return true;
    }

    private void response401(ServletRequest request, ServletResponse response) {
        //
        HttpServletResponse response1 = (HttpServletResponse) response;
        //重定向
        try {
            response1.sendRedirect("/401");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
